package com.googlecode.garbagecan.commons.execstudy;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;

public class Sample3 {
	
	private static Logger logger = Logger.getLogger(Sample3.class.getName());
	
	public static void main(String[] args) {
		test();
		testEnvironment();
	}

	public static void test() {
		CommandLine cmdLine = new CommandLine("cat");
		cmdLine.addArgument("${file}");
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("file", new File("pom.xml"));
		cmdLine.setSubstitutionMap(map);
		
		DefaultExecutor executor = new DefaultExecutor();
		ExecuteWatchdog watchdog = new ExecuteWatchdog(10 * 1000);
		executor.setWatchdog(watchdog);
		
		try {
			int exitValue = executor.execute(cmdLine);
			logger.log(Level.INFO, "Exit Value: " + exitValue);
		} catch (ExecuteException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		}
	}
	
	// test.sh
	//#!/bin/sh
	//echo $MYENV
	public static void testEnvironment() {
		CommandLine cmdLine = new CommandLine("./test.sh");
		DefaultExecutor executor = new DefaultExecutor();
		ExecuteWatchdog watchdog = new ExecuteWatchdog(10 * 1000);
		executor.setWatchdog(watchdog);
		
		try {
			Map<String, String> env = new HashMap<String, String>();
			env.put("MYENV", "Hi");
			int exitValue = executor.execute(cmdLine, env);
			logger.log(Level.INFO, "Exit Value: " + exitValue);
		} catch (ExecuteException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		}
	}
}
